<template>
  <el-row :gutter="0" class="register-form">
    <el-col :span="24">
      <el-form
        ref="registerFormRef"
        label-width="auto"
        :model="registerForm"
        :size="'large'"
        :rules="registerRules"
      >
        <el-form-item prop="username">
          <el-input
            type="text"
            name="username"
            placeholder="邮箱/手机号码/小米ID"
            v-model="registerForm.username"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            name="password"
            placeholder="密码"
            v-model="registerForm.password"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            type="password"
            name="confirmPassword"
            placeholder="确认密码"
            v-model="registerForm.confirmPassword"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="submit-btn"
            @click="handleRegister"
            color="#ff6700"
            :loading="loading"
            :disabled="buttonDisabled"
            >立即注册</el-button
          >
        </el-form-item>
        <div class="form-footer">
          <router-link :to="loginPage"> 已有账号？立即登录 </router-link>
        </div>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from "vue";
  import { useRouter } from "vue-router";
  import httpClient from "../../../utils/http";
  import { FormInstance, FormRules } from "element-plus";
  import { ElMessage } from "element-plus";

  interface RegisterForm {
    username: string;
    password: string;
    confirmPassword: string;
  }

  const registerFormRef = ref<FormInstance>();
  const loading = ref(false);

  const registerForm = reactive<RegisterForm>({
    username: "",
    password: "",
    confirmPassword: "",
  });

  const loginPage = {
    path: "/auth",
    query: { type: "login" },
  };

  const validatePass = (_rule: any, value: string, callback: any) => {
    if (value === "") {
      callback(new Error("请输入密码"));
    } else if (value.length < 6) {
      callback(new Error("密码长度不能小于6位"));
    } else {
      callback();
    }
  };

  const validateConfirmPass = (_rule: any, value: string, callback: any) => {
    if (value === "") {
      callback(new Error("请再次输入密码"));
    } else if (value !== registerForm.password) {
      callback(new Error("两次输入密码不一致"));
    } else {
      callback();
    }
  };

  const registerRules = reactive<FormRules>({
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      {
        min: 3,
        max: 20,
        message: "用户名长度在3-20个字符之间",
        trigger: "blur",
      },
    ],
    password: [{ required: true, validator: validatePass, trigger: "blur" }],
    confirmPassword: [
      { required: true, validator: validateConfirmPass, trigger: "blur" },
    ],
  });

  const router = useRouter();

  const buttonDisabled = computed(() => {
    return (
      !registerForm.username ||
      !registerForm.password ||
      !registerForm.confirmPassword ||
      loading.value
    );
  });

  const handleRegister = async () => {
    if (!registerFormRef.value) return;

    try {
      await registerFormRef.value.validate();
      loading.value = true;

      const response = await httpClient.post("/auth/register", {
        username: registerForm.username,
        password: registerForm.password,
      });

      if (response.status === 200 && response.data.code === 0) {
        ElMessage({
          type: "success",
          message: "注册成功",
          offset: 80,
        });
        router.push("/auth?type=login");
      } else {
        ElMessage({
          type: "error",
          message: response.data.message || "注册失败",
          offset: 80,
        });
      }
    } catch (error: any) {
      ElMessage({
        type: "error",
        message: error.message || "注册失败，请检查输入信息",
        offset: 80,
      });
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    registerFormRef.value?.resetFields();
  });
</script>

<style lang="scss" scoped>
  @use "@/styles/variable" as *;
  @use "sass:color";

  .submit-btn {
    width: 100%;
    height: 40px;
    font-size: 16px;
    color: $bsWhite;
  }

  :deep(.el-input--large .el-input__wrapper) {
    padding: 6px 15px;
  }

  .form-footer {
    text-align: center;
    margin-top: 20px;
    font-size: 14px;
    color: #666;

    a {
      color: $themeColor;
      text-decoration: none;
    }

    .divider {
      margin: 0 10px;
      color: #ddd;
    }
  }

  .register-form {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
